package com.hxkcloud.patient;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.util.Pair;
import android.view.View;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.controller.EaseUI;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.tencent.bugly.crashreport.CrashReport;
import com.hxkcloud.patient.aerotel.AerotelActivity;
import com.hxkcloud.patient.beans.RequestSecdataBean;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.utils.SystemUtils;
import com.hxkcloud.patient.views.LoadingDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by william_sun on 2016-09-23.
 * Description:
 */
public class YjhApplication extends Application {
    public static AerotelActivity aerotelActivity = null;
    public static int StatusBarHeight = 0;
    public static Context applicationContext;
    public static YjhApplication application;
    public static RequestSecdataBean secData;

    public static final String articlekind_news = "0";//资讯
    public static final String articlekind_course = "1";//课堂文章

    public static final String file_media = "media";//音频上传dir
    public static final String file_image = "image";//图片上传dir
    public static final String file_file = "file";//图片上传dir

    //0是测量1是文章2是文字
    public static final String doorder_type_check = "0";
    public static final String doorder_type_article = "1";
    public static final String doorder_type_content = "2";

    //4-doctor3-患者2-护士
    public static final String userstyle_nurse = "2";
    public static final String userstyle_patient = "3";
    public static final String userstyle_doctor = "4";

    //记录是否有新消息
    public static boolean msg_monitor = false;//监测提醒（医护）
    public static boolean msg_assessNurse = false;//评估提醒（医护）
    public static boolean msg_assessPatient = false;//评估提醒（患者）
    public static boolean msg_evalution = false;//患者端医生评价
    public static boolean msg_system = false;//系统消息
    public static boolean msg_chat = false;//环信聊天
    public static boolean msg_new = false;//全部判断

    //记录应用是否在前台
    public static boolean isAppActive = false;
    protected LoadingDialog loadingDialog;
    @Override
    public void onCreate() {
        super.onCreate();
        applicationContext = this;
        application = this;

        initImageLoader();

        initEM();
        JPushInterface.init(this);
        JPushInterface.setDebugMode(false);

        CrashReport.initCrashReport(getApplicationContext());
    }

    // 用于刷新UI
    private
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            dismisssLoading();
            if (msg.what == MessageCode.NETWORKCODE_CONNECT_ERROR) {
//                dismisssLoading();
//                toastMsg("网络异常，请检测网络");
            }
//            updateByHandler(msg);
        }
    };
    public static void initImageLoader() {
        //文件缓存路径
        File cacheDir = applicationContext.getExternalFilesDir("/dataCache");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(applicationContext)
                .memoryCacheExtraOptions(480, 800)//每个缓存文件的最大长宽
//			.discCacheExtraOptions(480, 800, null)//文件缓存图片处理方式，文件最大长宽，一般不设置此选项
                .threadPoolSize(3)//线程池内同时加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)//线程优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO)//设置图片加载和显示队列处理的类型
                .memoryCache(new LruMemoryCache(10 * 1024 * 1024))//设置内存缓存大小为5MB
                .memoryCacheSizePercentage(10)//设置内存缓存最大大小占当前应用可用内存的百分比
                .denyCacheImageMultipleSizesInMemory()//缓存显示不同大小的同一张图片
                .discCache(new UnlimitedDiskCache(cacheDir))//设置文件缓存路径
                .discCacheSize(50 * 1024 * 1024)//设置文件缓存大小为50MB
                .discCacheFileCount(100)//设置文件缓存数目最大为100
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())//文件缓存名称HashCode加密
                .imageDownloader(new BaseImageDownloader(applicationContext)) //图片下载方式
                .imageDecoder(new BaseImageDecoder(false)) //图片解码方式
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) //图片显示方式
                .build();
        ImageLoader.getInstance().init(config);
    }

    private void initEM() {
        //环信http://docs.easemob.com/im/200androidclientintegration/135easeuiuseguide
//        EMOptions options = new EMOptions();
        // 默认添加好友时，是不需要验证的，改成需要验证
//        options.setAcceptInvitationAlways(false);
//        options.setAppKey("yijiahu2015#yjhcloud");
        //初始化
//        EMClient.getInstance().init(applicationContext, options);
        //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
//        EMClient.getInstance().setDebugMode(true);
        EaseUI.getInstance().init(this, null);

    }

    public static YjhApplication getInstance() {
        return application;
    }

    public static void initSecData() {
        secData = new RequestSecdataBean();

        secData.setApp_from("Android_Developer");
        secData.setApp_id("1");
        secData.setApp_version(SystemUtils.getVersionCode(getInstance()) + "");
        secData.setDevice_name(Build.MODEL);
        secData.setDevice_type("android");
        secData.setIdentify_key(SystemUtils.getIdentify_key(getInstance()));
        secData.setLanguage(Locale.getDefault().getLanguage().toString());
        secData.setRecord("1");
        secData.setNetwork_type(SystemUtils.getNetwork_type(getInstance()));
        secData.setVersion(Build.VERSION.RELEASE);
        secData.setApp("2");

    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    /**
     * 穿入点击数量文本
     *
     * @param msg_number
     */
    public void showMsg(TextView msg_number) {
        if (msg_number == null)
            return;
        int num = getMsgNum();
        if (num == 0) {
            msg_number.setText("");
            msg_number.setVisibility(View.GONE);
        } else {
            if (num > 99) {
                msg_number.setText("...");
            } else {
                msg_number.setText("" + num);
            }
            msg_number.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取消息数量
     *
     * @return int
     */
    public int getMsgNum() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        int num = 0;
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                EMConversation emConversation = list.get(i);
                num += emConversation.getUnreadMsgCount();
            }
            return num;
        } else {
            return 0;

        }
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

}
